﻿using ImGuiNET;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
using TTEditor;

namespace FakeUnity.Editor
{
    class WindowScene : IWindow
    {
        public WindowScene()
        {

        }
        public void OnClose()
        {
        }
        public bool candock => true;
        Vector2 winsize;
        Warp.FrameworkNative.TargetHandle target = new Warp.FrameworkNative.TargetHandle();
        IntPtr targetTexture = IntPtr.Zero;
        int targetW;
        int targetH;

        Warp.FrameworkNative.Material mat;
        Warp.FrameworkNative.Mesh mesh;
        public void OnUpdate()
        {
            if (mat.ptr == IntPtr.Zero)
            {
                mat = Warp.FrameworkNative.Material_Create("nihaoma");
                mesh = Warp.FrameworkNative.Mesh_CreateSample();
            }
            var w = (int)winsize.X;
            var h = (int)winsize.Y;
            if (w == 0 || h == 0)
                return;
            if (target.ptr == IntPtr.Zero)
            {
                targetW = w;
                targetH = h;
                target = FakeUnity.Warp.FrameworkNative.Target_Create(w, h);

            }
            else if (w != targetW || h != targetH)
            {
                targetW = w;
                targetH = h;
                Warp.FrameworkNative.Target_Reset(target, w, h);
            }

            //render frame
            Warp.FrameworkNative.Frame_SetTarget(target);//0xRGBA

            Warp.FrameworkNative.Frame_Clear(0x000033ff, true, true);
            Warp.FrameworkNative.Frame_Draw(mat, mesh);
            {
                Warp.FrameworkNative.Frame_Clear(0, false, true);//試試clear depth 能不能在中間發生
            }
            Warp.FrameworkNative.Frame_Flush();
        }
        public void OnGUI()
        {
            Vector2 canvas_p = ImGui.GetCursorScreenPos();       // ImDrawList API uses screen coordinates!
            Vector2 canvas_sz = ImGui.GetContentRegionAvail();   // Resize canvas to what's available

            winsize = canvas_sz;
            if (target.ptr != IntPtr.Zero)
            {
                var texid = Warp.FrameworkNative.Target_GetImGuiTexID(target);
                ImGui.Image(texid, winsize);
            }
        }

        public void Show()
        {
        }
    }
}
